﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

using System.Data.Entity;
using System.Configuration;
using Yala.DataAccess.Common.EF.Mappings;
using Yala.Core.Domain;

namespace Yala.DataAccess.Common.EF {
    public abstract class EFRepositoryBase<T> : DbContext, IRepository<T> where T : class, new() {

        public DbSet<T> Items { get; set; }

        public EFRepositoryBase()
            : this(ConfigurationManager.ConnectionStrings[Environment.MachineName].ConnectionString) {
        }

        public EFRepositoryBase(string connectionString)
            : base(connectionString) {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder) {
            modelBuilder.Configurations.Add(new AuthProviderConfiuration());
            modelBuilder.Configurations.Add(new UserConfiguration());
            modelBuilder.Configurations.Add(new ItemConfiguration());
            modelBuilder.Configurations.Add(new UserProfileConfiguration());
        }
        

        public void Add(T item) {
            Items.Add(item);
        }

        public void Add(IEnumerable<T> items) {
            items.ToList().ForEach(x => this.Add(x));
        }

        public void Update(T item) {
            Items.Attach(item);
        }

        public void Delete(Expression<Func<T, bool>> expression) {
            var item = Single(expression);
            Delete(item);
        }

        public void Delete(T item) {
            Items.Remove(item);
        }

        public void DeleteAll() {
        }

        public void CommitChanges() {
            this.SaveChanges();
        }

        public T Single(Expression<Func<T, bool>> expression) {
            return Items.Where(expression).FirstOrDefault();
        }

        public IQueryable<T> All() {
            return Items;
        }

        public void Dispose() {
            base.Dispose();
        }
    }
}
